import { api } from 'poros/utils';
import router from '@/router';
import { clearLoginInfo, jumpLogin } from '@/utils/login';

const { getUserInfo, login, logout } = api;

export default {
  state: {
    userInfo: {},
    uid: '',
    name: '',
    avatar: '',

    // 当前用户所属租户列表
    tenantList: [],
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    setUserId(state, uid) {
      state.uid = uid;
      console.log(uid);
    },
    setUserName(state, name) {
      state.name = name;
    },
    setUserAvatar(state, avatar) {
      state.avatar = avatar;
    },
    setTenantList(state, tenantList) {
      state.tenantList = tenantList;
    },
  },
  actions: {
    requireUserInfo({ commit }) {
      return getUserInfo()
        .then(res => {
          if (res.code === 0) {
            commit('setUserInfo', res.data);
            commit('setUserId', res.data.uid);
            commit('setUserName', res.data.name);
            commit('setUserAvatar', res.data.headUrl);
          } else {
            throw new Error(res.msg);
          }
        })
        .catch(err => {
          throw err;
        });
    },
    login(_, params) {
      return login({ ...params }).then(res => {
        if (res.code === 0) {
          router.push('/').catch(() => {});
        }
        return res;
      });
    },
    logout() {
      // 脱出登录 请求，后端用于清空相关缓存
      logout();
      // 清空前端登录缓存信息
      clearLoginInfo();
      // 跳转登录页
      jumpLogin();
    },
  },
};
